/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Observable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Jacek
 */
public class ClientModel implements Runnable {

    String name;
    Socket server = null;
    String address = null;
    int port;
    private PrintWriter out = null;
    private BufferedReader in = null;
    boolean active;
    Thread listing;
    boolean getingList;
    public boolean listRead;
    String[] userlist;
    String buffor;
    public ViewI view;
    
    public ClientModel() {
        active = false;
    }

    public void Connect(String address, int port, String clientName) throws IOException {
        this.port = port;
        this.address = address;
        server = new Socket(address, port);
        out = new PrintWriter(server.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(server.getInputStream()));
        active = true;
        name = clientName;
        out.println(name);
        listing = new Thread(this);
        listing.start();
        getingList = false;
        listRead = false;
    }

    public void SendMassage(String text) {
        out.println(name + ":" + text);
        if (text.equals("quit")) {
            try {
                Disconnect();
            } catch (IOException ex) {
                Logger.getLogger(ClientModel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public String ReadMassage() throws IOException {
        return in.readLine();
    }

    public void Disconnect() throws IOException {
        out.println("quit");
        out.close();
        in.close();
        active = false;
    }

    public void GetUserList() throws IOException {
        out.println("list");
        getingList = true;
    }

    @Override
    public void run() {
        
        while (active) {
            try {
                    buffor = in.readLine();
                    
                    if (getingList){
                        userlist = buffor.split(", ");
                        if (userlist[0].equals("@list")) {
                            getingList=false;
                            view.AddList(userlist);
                        }
                    } else
                        view.AddComment(buffor);
                    
            } catch (IOException ex) {
                Logger.getLogger(ClientModel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    String GetBuffor() {
       return buffor;
    }
}
